<!--  -->
<template>
    <div class="overflow-hidden">
        <div data-tauri-drag-region class="titlebar bg-gradient-to-br from-black to-gray-600">
            <div data-tauri-drag-region style="
          margin-right: auto;
          display: inline-flex;
          justify-content: center;
          align-items: center;
          margin-left: 10px;
          font-size: 10pt;
        ">
                {{ info }}
            </div>
            <div class="titlebar-button" id="titlebar-minimize">
                <el-icon>
                    <Minus />
                </el-icon>
            </div>
            <div class="titlebar-button" id="titlebar-maximize">
                <el-icon>
                    <Plus />
                </el-icon>
            </div>
            <div class="titlebar-button" id="titlebar-close">
                <el-icon>
                    <Close />
                </el-icon>
            </div>
        </div>

        <div class="mt-10 p-2 bg-gradient-to-b from-black to-gray-600 overflow-hidden">
            <el-upload class="upload-demo" drag :before-upload="uploadFile" multiple>
                <el-icon class="el-icon--upload">
                    <svg t="1691048505346" class="icon" viewBox="0 0 1024 1024" version="1.1"
                        xmlns="http://www.w3.org/2000/svg" p-id="7060" width="100" height="100" style="margin: 0 auto">
                        <path
                            d="M872.448 939.008H151.552l-40.96-40.96V299.008l40.96-40.96h158.72v81.92H192.512v517.12h638.976V339.968H713.728v-81.92h158.72l40.96 40.96v599.04z"
                            fill="#437DFF" p-id="7061"></path>
                        <path
                            d="M387.072 229.376l-34.816-50.176 138.24-94.208h34.816l131.072 94.208-35.84 50.176-113.664-81.92z"
                            fill="#63F7DE" p-id="7062"></path>
                        <path d="M473.088 137.216h61.44v370.688h-61.44z" fill="#63F7DE" p-id="7063"></path>
                    </svg>
                </el-icon>
                <div class="el-upload__text">
                    拖动文件到这里或 <em>点击这里选文件</em>
                </div>
            </el-upload>
        </div>

        <el-menu class="w-full h-96 overflow-y-auto overflow-x-hidden">
            <el-menu-item v-for="(f, i) in ll" v-bind:key="i" :index="f.name" class="text-black">
                <el-icon v-if="f.isOpen">
                    <Star class="text-yellow-600" />
                </el-icon>
                <el-tooltip class="box-item" effect="dark" :content="f.inputtime" placement="left">

                    <el-tag class="mr-4">{{ f.sorttime }}</el-tag>

                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" :content="f.name" placement="left">
                    <div @click="openfileview(f)"> {{ f.name }} </div>

                </el-tooltip>
                <div class="absolute right-10" @click="copyText2(f.name)">
                    <el-icon>
                        <DocumentCopy class="text-blue-600" />
                    </el-icon>
                </div>
                <div class="absolute right-0" @click="delCos(f.name)">
                    <el-icon>
                        <Close class="text-red-600" />
                    </el-icon>
                </div>
            </el-menu-item>
        </el-menu>
    </div>
</template>

<script>
import { appWindow, WebviewWindow } from "@tauri-apps/api/window";
import { emit, listen } from '@tauri-apps/api/event'
import { getClient, ResponseType } from '@tauri-apps/api/http';
import { _, forEach } from "lodash";
import dayjs from 'dayjs';
// 如果需要处理 UTC 时间

import COS from "cos-js-sdk-v5";
// 存储桶名称，由 bucketname-appid 组成，appid 必须填入，可以在 COS 控制台查看存储桶名称。 https://console.cloud.tencent.com/cos5/bucket
const Bucket = import.meta.env.VITE_COS_Bucket; /* 存储桶，必须字段 */

// 存储桶 region 可以在 COS 控制台指定存储桶的概览页查看 https://console.cloud.tencent.com/cos5/bucket/
// 关于地域的详情见 https://cloud.tencent.com/document/product/436/6224
const Region = import.meta.env.VITE_COS_Region; /* 存储桶所在地域，必须字段 */

var cos = new COS({
    SecretId: import.meta.env.VITE_COS_SecretId,
    SecretKey: import.meta.env.VITE_COS_SecretKey,
});
import { isPermissionGranted, requestPermission, sendNotification } from '@tauri-apps/api/notification';
(async () => {
    let permissionGranted = await isPermissionGranted();
    if (!permissionGranted) {
        const permission = await requestPermission();
        permissionGranted = permission === 'granted';
    }
})();
export default {
    data() {
        return {
            ll: [],
            info: "",
        };
    },

    components: {},

    computed: {},

    mounted() {

        this.coslist();
        document
            .getElementById("titlebar-minimize")
            .addEventListener("click", () => appWindow.minimize());
        document
            .getElementById("titlebar-maximize")
            .addEventListener("click", () => appWindow.toggleMaximize());
        document
            .getElementById("titlebar-close")
            .addEventListener("click", () => appWindow.close());
        listen("cos", (event) => {

            console.log(event.payload.data);
            const r = event.payload.data;
            let position = this.ll.findIndex(item => item.name === r.name);
            console.log(r);
            this.ll[position].isOpen = false;
        });
    },

    created() { },

    methods: {
        d(key) {
            return new Promise((resolve, reject) => {
                cos.getObjectUrl(
                    {
                        Bucket: Bucket,
                        Region: Region,
                        Key: key,
                        Sign: false,
                        Protocol: "https:"
                    },
                    (err, data) => {
                        if (err) {
                            console.error(err);
                            reject(err);
                        } else {
                            console.log(data);
                            resolve(data.Url);
                        }
                    }
                );
            });
        },
        f(key) {
            return new Promise((resolve, reject) => {

                cos.getObject(
                    {
                        Bucket: Bucket,
                        Region: Bucket,
                        Protocol: "https:",
                        Key: key,

                    },
                    (err, data) => {
                        if (err) {
                            console.error(err);
                            reject(err);
                        } else {
                            console.log(data);
                            resolve(data.Body);
                        }
                    }
                );


            });
        },
        async copyText2(text) {
            console.log("copyText2");

            const u = await this.d(text);
            navigator.clipboard
                .writeText(u)
                .then(() => {
                    console.log("已成功复制到剪贴板");

                    if (permissionGranted) {
                        //sendNotification('Tauri is awesome!');
                        sendNotification({ title: '通知', body: '文件地址复制成功!' });
                    }

                })
                .catch((error) => {
                    console.error("复制失败：", error);
                });
        },
        async openfileview(f) {
            var label = _.replace(f.name, /[-/:_.]/g, '');
            let position = this.ll.findIndex(item => JSON.stringify(item) === JSON.stringify(f));
            this.ll[position].isOpen = true
            console.log(position);
            const windowConfig = {
                url: "#/f?label=" + label,
                title: f.name,
                center: true,
                width: 800,
                height: 600,

                // 可自行添加属性配置     窗口配置
                //center: true,
                decorations: false
            }

            const url = await this.d(f.name);
            console.log(label);
            const client = await getClient();
            const res = await client.get(url, {
                timeout: 30,
                // the expected response type
                responseType: ResponseType.Text
            });
            const content = res.data
            console.log(content);
            const w = WebviewWindow.getByLabel(label);

            if (w != null) {
                console.log(w);
                await w.setFocus();
            }
            else {

                const webview = new WebviewWindow(label, windowConfig);

                webview.once("tauri://created", function () {
                    // webview window successfully created
                    // 窗口创建成功 打印1


                    setTimeout(() => {
                        emit(label, { data: { name: f.name, url: url, content: content } });
                        console.log(1);
                    }, 1000); // 例如延迟1秒
                    console.log(1);
                });
                webview.once("tauri://error", function (e) {
                    // an error happened creating the webview window
                    // 窗口创建失败 打印2
                    console.log(2);
                });
                let that = this;
                webview.once("tauri://close-requested", function (e) {
                    // an error happened creating the webview window
                    // 窗口创建失败 打印2






                });
            }
        },
        async coslist() {
            let that = this;
            that.ll = [];
            await cos.getBucket(
                {
                    Bucket: Bucket /* 填入您自己的存储桶，必须字段 */,
                    Region: Region /* 存储桶所在地域，例如ap-beijing，必须字段 */,
                    Prefix: "" /* Prefix表示列出的object的key以prefix开始，非必须 */,
                },
                function (err, data) {
                    console.log(err || data);
                    var filecount = 0;
                    var filesize = 0;
                    forEach(
                        data.Contents,
                        function (item) {
                            //console.log("item: ", item);
                            const id = item.ETag;
                            const name = item.Key;
                            const status = "finished";
                            const LastModified = item.LastModified;
                            const inputtime = dayjs(item.LastModified).format('YYYY-MM-DD HH:mm:ss');
                            const sorttime = dayjs(item.LastModified).format('M-DD HH:mm');
                            // 创建一个包含id和name的新对象，并将其添加到filelist集合中
                            that.ll.push({ id, name, status, LastModified, inputtime, sorttime });

                            filecount += 1;
                            filesize += parseInt(item.Size);
                        }.bind(this)
                    );
                    that.$forceUpdate();
                    const sortedArray = _.orderBy(that.ll, ["LastModified"], ["desc"]);
                    that.ll = sortedArray;
                    that.info =
                        "共有" +
                        filecount +
                        "个文件，总大小为" +
                        (filesize / 1024 / 1024).toFixed(2) +
                        "MB";
                    //console.log(sortedArray);
                    console.log("ll: ", that.ll);
                }
            );
        },

        async uploadFile(file) {
            console.log("file: ", file);
            let that = this;

            const result = await cos.putObject(
                {
                    Bucket: Bucket /* 填入您自己的存储桶，必须字段 */,
                    Region: Region /* 存储桶所在地域，例如ap-beijing，必须字段 */,
                    Key: file.name,
                    Body: file,

                    onProgress: function (progressData) {
                        console.log(JSON.stringify(progressData));
                    },
                },
                function (err, data) {
                    if (err) {
                        console.log("上传失败", err);
                    } else {
                        that.coslist();
                        if (permissionGranted) {
                            // sendNotification('Tauri is awesome!');
                            sendNotification({ title: '通知', body: '文件上传成功!' });
                        }
                        console.log("上传成功");
                    }
                }
            );
        },
        async delCos(key) {
            let that = this;
            cos.deleteObject({
                Bucket: Bucket, /* 填写自己的 bucket，必须字段 */
                Region: Region,     /* 存储桶所在地域，必须字段 */
                Key: key,              /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
            }, function (err, data) {
                console.log(data);
                if (data.statusCode == 204 || data.statusCode == 200) {
                    if (permissionGranted) {
                        // sendNotification('Tauri is awesome!');
                        sendNotification({ title: '通知', body: '文件删除成功!' });
                    }
                    that.coslist();
                }

            });

        }
    },
};
</script>
<style lang='scss' scoped></style>